package com.mashibing.remote;

import com.mashibing.internalcommon.constant.AmapConfigConstants;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.response.TerminalResponse;
import com.mashibing.internalcommon.response.TrackResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class AddTrackClient {


    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String sid;


    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult<TrackResponse> addTrack(String tid) {
        // 组装url
        StringBuilder urlBuild = new StringBuilder();
        urlBuild.append(AmapConfigConstants.TRACK_ADD);
        urlBuild.append("?");
        urlBuild.append("key=" + amapKey);
        urlBuild.append("&");
        urlBuild.append("tid=" + tid);
        urlBuild.append("&");
        urlBuild.append("sid=" + sid);
        log.info("高德地图：创建轨迹：" + urlBuild);

        // 请求远程地址
        ResponseEntity<String> directionEntity = restTemplate.postForEntity(urlBuild.toString(), null,String.class);
        JSONObject result = JSONObject.fromObject(directionEntity.getBody());
        String trid = result.getJSONObject("data").getString("trid");

        TrackResponse trackResponse = new TrackResponse();
        trackResponse.setTrid(trid);
        log.info("高德地图：创建轨迹trid为：" + trid);

        return ResponseResult.success(trackResponse);
    }
}
